package com.example.jetpack

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingSource
import androidx.paging.PagingState
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.jetpack.learn.Item
import com.example.jetpack.learn.MyDataSource
import com.example.jetpack.learn.MyPagingDataAdapter
import kotlinx.coroutines.flow.asFlow
import java.io.IOException
import java.net.HttpRetryException

class MainActivity : AppCompatActivity() {

    private lateinit var rv : RecyclerView
    private val adapter by lazy {
//        RecyclerPagingAdapter()
        MyPagingDataAdapter()
    }
    private lateinit var viewModel : StudentViewModel


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        rv = findViewById<RecyclerView>(R.id.recyclerView)

        viewModel =   ViewModelProvider(this,ViewModelProvider.NewInstanceFactory())[StudentViewModel::class.java]



        /*viewModel.listLiveData.observe(this){
            adapter.submitList(it)
        }
        adapter.notifyItemChanged(0,1)
*/

        rv.adapter = adapter
        rv.layoutManager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)



        MyDataSource(source)

    }



    /**
     * 数据的来源： 数据库、文件、网络服务器...
     */
    val source : (Int) -> MutableList<Item> = { pageSize ->
        val result = mutableListOf<Item>()
        var startPosition = if (pageSize >= 0 ) pageSize * 20 else 0
        for (i in startPosition until (startPosition + pageSize) ){
            result.add(Item(i,"姓名： $i"))
        }
        result
    }
}
